package com.synface.utils;

import android.annotation.SuppressLint;
import android.os.Environment;
import android.text.TextUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class FileUtils
{
  public static final String APP_ABSOLUTEPATH = Environment.getExternalStorageDirectory().getPath();
  public static String THUMBNAIL_PATH;
  public static String TEMP_PATH;
  public static String EXTERNAL_CACHE_DIR;
  public static final String FILE_EXTENSION_SEPARATOR = ".";

  private FileUtils()
  {
    throw new AssertionError();
  }

  public static StringBuilder readFile(String filePath, String charsetName)
  {
    File file = new File(filePath);
    StringBuilder fileContent = new StringBuilder("");
    if ((file == null) || (!file.isFile())) {
      return null;
    }

    BufferedReader reader = null;
    try {
      InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
      reader = new BufferedReader(is);
      String line = null;
      while ((line = reader.readLine()) != null) {
        if (!fileContent.toString().equals("")) {
          fileContent.append("\r\n");
        }
        fileContent.append(line);
      }
      reader.close();
      StringBuilder localStringBuilder1 = fileContent;

      return localStringBuilder1;
    }
    catch (IOException e)
    {
    }
    finally
    {
      if (reader != null)
        try {
          reader.close();
        } catch (IOException e) {
          throw new RuntimeException("IOException occurred. ", e);
        }
    }
    return null;
  }

  public static byte[] readFile(String filePath)
  {
    File file = new File(filePath);
    long fileSize = file.length();
    if ((file == null) || (!file.isFile())) {
      return null;
    }

    InputStream is = null;
    try {
      is = new FileInputStream(file);
      byte[] buffer = new byte[(int)fileSize];
      int offset = 0;
      int numRead = 0;
      while ((offset < buffer.length) && 
        ((numRead = is
        .read(buffer, offset, buffer.length - offset)) >= 0))
      {
        offset += numRead;
      }

      if (offset != buffer.length)
      {
        throw new IOException(new StringBuilder().append("Could not completely read file ")
          .append(file
          .getName()).toString());
      }
      is.close();
      byte[] arrayOfByte1 = buffer;

      return arrayOfByte1;
    }
    catch (IOException e)
    {
    }
    finally
    {
      if (is != null)
        try {
          is.close();
        } catch (IOException e) {
          throw new RuntimeException("IOException occurred. ", e);
        }
    }
    return null;
  }

  public static boolean writeFile(String filePath, String content, boolean append)
  {
    if (isEmpty(content)) {
      return false;
    }

    FileWriter fileWriter = null;
    try {
      makeDirs(filePath);
      fileWriter = new FileWriter(filePath, append);
      fileWriter.write(content);
      fileWriter.close();

      return true;
    }
    catch (IOException e)
    {
    }
    finally
    {
      if (fileWriter != null)
        try {
          fileWriter.close();
        } catch (IOException e) {
          throw new RuntimeException("IOException occurred. ", e);
        }
    }
    return false;
  }

  public static boolean writeFile(String filePath, byte[] bytes)
  {
    if (bytes == null) {
      return false;
    }
    File outputFile = new File(filePath);
    FileOutputStream outputFileStream = null;
    try {
      makeDirs(filePath);
      outputFileStream = new FileOutputStream(outputFile);
      outputFileStream.write(bytes);
      outputFileStream.close();
      return true;
    }
    catch (IOException e)
    {
    }
    finally
    {
      if (outputFileStream != null)
        try {
          outputFileStream.close();
        } catch (IOException e) {
          throw new RuntimeException("IOException occurred. ", e);
        }
    }
    return false;
  }

  public static boolean writeFile(String filePath, String content)
  {
    return writeFile(filePath, content, false);
  }

  public static boolean writeFile(String filePath, InputStream stream)
  {
    return writeFile(filePath, stream, false);
  }

  public static boolean writeFile(String filePath, InputStream stream, boolean append)
  {
    return writeFile((filePath != null) ? new File(filePath) : null, stream, append);
  }

  public static boolean writeFile(File file, InputStream stream)
  {
    return writeFile(file, stream, false);
  }

  public static boolean writeFile(File file, InputStream stream, boolean append)
  {
    OutputStream o = null;
    try {
      makeDirs(file.getAbsolutePath());
      o = new FileOutputStream(file, append);
      byte[] data = new byte[1024];
      int length = -1;
      while ((length = stream.read(data)) != -1) {
        o.write(data, 0, length);
      }
      o.flush();
      return true;
    }
    catch (FileNotFoundException e)
    {
    }
    catch (IOException e)
    {
    }
    finally
    {
      if (o != null)
        try {
          o.close();
          stream.close();
        } catch (IOException e) {
          throw new RuntimeException("IOException occurred. ", e);
        }
    }
    return false;
  }

  public static void moveFile(String sourceFilePath, String destFilePath)
  {
    if ((TextUtils.isEmpty(sourceFilePath)) || (TextUtils.isEmpty(destFilePath))) {
      throw new RuntimeException("Both sourceFilePath and destFilePath cannot be null.");
    }
    moveFile(new File(sourceFilePath), new File(destFilePath));
  }

  public static void moveFile(File srcFile, File destFile)
  {
    boolean rename = srcFile.renameTo(destFile);
    if (!rename) {
      copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
      deleteFile(srcFile.getAbsolutePath());
    }
  }

  public static boolean copyFile(String sourceFilePath, String destFilePath)
  {
    InputStream inputStream = null;
    try {
      inputStream = new FileInputStream(sourceFilePath);
    } catch (FileNotFoundException e) {
      throw new RuntimeException("FileNotFoundException occurred. ", e);
    }
    return writeFile(destFilePath, inputStream);
  }

  public static List<String> readFileToList(String filePath, String charsetName)
  {
    File file = new File(filePath);
    List fileContent = new ArrayList();
    if ((file == null) || (!file.isFile())) {
      return null;
    }

    BufferedReader reader = null;
    try {
      InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
      reader = new BufferedReader(is);
      String line = null;
      while ((line = reader.readLine()) != null) {
        fileContent.add(line);
      }
      reader.close();

      return fileContent;
    }
    catch (IOException e)
    {
    }
    finally
    {
      if (reader != null)
        try {
          reader.close();
        } catch (IOException e) {
          throw new RuntimeException("IOException occurred. ", e);
        }
    }
    return null;
  }

  public static String getFileNameWithoutExtension(String filePath)
  {
    if (isEmpty(filePath)) {
      return filePath;
    }

    int extenPosi = filePath.lastIndexOf(".");
    int filePosi = filePath.lastIndexOf(File.separator);
    if (filePosi == -1) {
      return (extenPosi == -1) ? filePath : filePath.substring(0, extenPosi);
    }
    if (extenPosi == -1) {
      return filePath.substring(filePosi + 1);
    }
    return (filePosi < extenPosi) ? filePath.substring(filePosi + 1, extenPosi) : filePath.substring(filePosi + 1);
  }

  public static String getFileName(String filePath)
  {
    if (isEmpty(filePath)) {
      return filePath;
    }

    int filePosi = filePath.lastIndexOf(File.separator);
    return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
  }

  public static String getFolderName(String filePath)
  {
    if (isEmpty(filePath)) {
      return filePath;
    }

    int filePosi = filePath.lastIndexOf(File.separator);
    return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
  }

  public static String getFileExtension(String filePath)
  {
    if (isBlank(filePath)) {
      return filePath;
    }

    int extenPosi = filePath.lastIndexOf(".");
    int filePosi = filePath.lastIndexOf(File.separator);
    if (extenPosi == -1) {
      return "";
    }
    return (filePosi >= extenPosi) ? "" : filePath.substring(extenPosi + 1);
  }

  public static boolean makeDirs(String filePath)
  {
    String folderName = getFolderName(filePath);
    if (isEmpty(folderName)) {
      return false;
    }

    File folder = new File(folderName);
    return ((folder.exists()) && (folder.isDirectory())) ? true : folder.mkdirs();
  }

  public static boolean makeFolders(String filePath)
  {
    return makeDirs(filePath);
  }

  public static boolean isFileExist(String filePath)
  {
    if (isBlank(filePath)) {
      return false;
    }

    File file = new File(filePath);
    return (file.exists()) && (file.isFile());
  }

  public static boolean isFolderExist(String directoryPath)
  {
    if ((directoryPath == null) || (directoryPath.trim().length() == 0)) {
      return false;
    }

    File dire = new File(directoryPath);
    return (dire.exists()) && (dire.isDirectory());
  }

  public static boolean deleteFile(String path)
  {
    if ((path == null) || (path.trim().length() == 0)) {
      return true;
    }

    File file = new File(path);
    if (!file.exists()) {
      return true;
    }
    if (file.isFile()) {
      return file.delete();
    }
    if (!file.isDirectory()) {
      return false;
    }
    for (File f : file.listFiles()) {
      if (f.isFile())
        f.delete();
      else if (f.isDirectory()) {
        deleteFile(f.getAbsolutePath());
      }
    }
    return file.delete();
  }

  public static long getFileSize(String path)
  {
    if (isBlank(path)) {
      return -1L;
    }

    File file = new File(path);
    return ((file.exists()) && (file.isFile())) ? file.length() : -1L;
  }

  @SuppressLint({"SimpleDateFormat"})
  public static String getRandomName() {
    UUID uuid = UUID.randomUUID();
    Date now = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String name = dateFormat.format(now);
    return new StringBuilder().append(uuid.toString()).append(".jpg").toString();
  }

  public static String getRandomStr() {
    UUID uuid = UUID.randomUUID();
    return uuid.toString();
  }

  public static void clearThumbnailDir() {
    File file = new File(THUMBNAIL_PATH);
    if (!file.exists()) {
      return;
    }
    File[] files = file.listFiles();
    for (File f : files)
      if (f.isFile())
        f.delete();
  }

  public static void clearThumbnailDirAsync()
  {
    new Thread(new Runnable()
    {
      public void run() {
        FileUtils.clearThumbnailDir();
      }
    }).start();
  }

  private static ArrayList<String> getDevMountList()
  {
    String[] toSearch = readFile("/etc/vold.fstab", "utf8").toString().split(" ");
    ArrayList out = new ArrayList();
    for (int i = 0; i < toSearch.length; ++i) {
      if ((!toSearch[i].contains("dev_mount")) || 
        (!new File(toSearch[(i + 2)]).exists())) continue;
      out.add(toSearch[(i + 2)]);
    }

    return out;
  }

  public static String getExternalSdCardPath()
  {
    if ("mounted".equals(Environment.getExternalStorageState().toLowerCase())) {
      File sdCardFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
      return sdCardFile.getAbsolutePath();
    }

    String path = null;

    File sdCardFile = null;

    ArrayList<String> devMountList = getDevMountList();

    for (String devMount : devMountList) {
      File file = new File(devMount);

      if ((file.isDirectory()) && (file.canWrite())) {
        path = file.getAbsolutePath();

        String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
        File testWritable = new File(path, new StringBuilder().append("test_").append(timeStamp).toString());

        if (testWritable.mkdirs())
          testWritable.delete();
        else {
          path = null;
        }
      }
    }

    if (path != null) {
      sdCardFile = new File(path);
      return sdCardFile.getAbsolutePath();
    }

    return null;
  }

  public static boolean isBlank(String str) {
    return (str == null) || (str.trim().length() == 0);
  }

  public static boolean isEmpty(CharSequence str) {
    return (str == null) || (str.length() == 0);
  }
}